package com.leetcode;

import com.leetcode.common.TreeNode;
import com.leetcode.util.BinaryTreeUtil;

/**
 * 450. 删除二叉搜索树中的节点
 *
 * @author fy
 * @date 2022/4/26 18:23
 */
public class Solution450_2 {

    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) {
            return null;
        }
        if (root.val > key) {
            root.left = deleteNode(root.left, key);
        } else if (root.val < key) {
            root.right = deleteNode(root.right, key);
        } else {
            // 要删除的节点是叶子节点
            if (root.left == null && root.right == null) {
                return null;
            } else if (root.left != null) {
                root.val = predecessor(root);
                root.left = deleteNode(root.left, root.val);
            } else {
                root.val = successor(root);
                root.right = deleteNode(root.right, root.val);
            }
        }
        return root;
    }

    /**
     * 在root的子树中, 查找root的前驱值
     *
     * @param root
     * @return
     */
    private int predecessor(TreeNode root) {
        root = root.left;
        while (root.right != null) {
            root = root.right;
        }
        return root.val;
    }

    /**
     * 在root的子树中, 查找root的后继值
     *
     * @param root
     * @return
     */
    private int successor(TreeNode root) {
        root = root.right;
        while (root.left != null) {
            root = root.left;
        }
        return root.val;
    }

    public static void main(String[] args) {
        TreeNode root = BinaryTreeUtil.createTree(new Integer[]{5, 3, 6, 2, 4, null, 7});
        int key = 6;
        BinaryTreeUtil.printTree(root);

        TreeNode newRoot = new Solution450_2().deleteNode(root, key);
        BinaryTreeUtil.printTree(newRoot);
    }

}
